<template>
    <div class="home">
        <!--蓝色头部-->
        <div class="userinfo">
            <div class="avatar fl" :style="{backgroundImage: 'url('+ avatar +')'}">
            </div>
            <div class="text fl">
                <div class="username">
                    {{userInfo.userName}}
                </div>
                <div class="account">
                    账号：{{userInfo.userNum}}
                </div>
            </div>
            <router-link class="credit" :to="'/mycredit'">
                信用等级:
                <!--<span class="rank" :style="{backgroundImage: 'url('+ starsmall +')'}"></span>-->
                <!--<span class="rank" :style="{backgroundImage: 'url('+ starsmall +')'}"></span>-->
                <span class="rank" :style="{backgroundImage: 'url('+ starsmall +')'}"
                      v-for="i in creditRank" v-if="creditRank"></span>
                <img :src="arrow" class="arrow">
            </router-link>
        </div>
        <!--我的报销-->
        <div class="baoxiao card">
            <div class="top clear line ">
                <div class="text fl">
                    我的报销
                </div>
                <router-link class="sub arrow fr" :to="'/mybaoxiao?index=0'">
                    查看全部
                </router-link>
            </div>
            <div class="card-main tx-c clear of-hide">
                <router-link class="item fl" v-for="i in 5" :to="'/mybaoxiao?index=' + i" :key="i">
                    <span class="badge ten" v-if="nums[i-1] > 9">{{nums[i-1]}}</span>
                    <span class="badge" v-else v-show="nums[i-1] > 0">{{nums[i-1]}}</span>
                    <div class="img">
                        <img :src="baoxiao[i-1].img" class="icon">
                    </div>
                    <p class="text">{{baoxiao[i - 1].name}}</p>
                </router-link>
            </div>
        </div>
        <!--常用功能-->
        <div class="common card">
            <div class="top clear line ">
                <div class="text fl">
                    常用功能
                </div>
            </div>
            <div class="card-main tx-c clear of-hide">
                <router-link class="item fl" v-for="i in 5" :to="common[i-1].url"
                             :class="{second:i>4}" :key="i">
                    <div class="img">
                        <img :src="common[i-1].img" class="icon" :class="common[i-1].type">
                    </div>
                    <p class="text">{{common[i - 1].name}}</p>
                </router-link>
            </div>
        </div>
        <!--单据查询-->
        <div class="query card">
            <div class="top clear line ">
                <div class="text fl">
                    单据查询
                </div>
                <router-link class="sub arrow fr" :to="'/billall'">
                    查看全部
                </router-link>
            </div>
            <div class="card-main tx-c clear of-hide">
                <a class="item fl" v-for="i in 8"
                   @click="goToDetail(chaxun[i-1].name, chaxun[i-1].img)"
                   :class="{second:i>4}">
                    <div class="img">
                        <img :src="chaxun[i-1].img" class="icon" :class="chaxun[i-1].type">
                    </div>
                    <p class="text">{{chaxun[i - 1].name}}</p>
                </a>
            </div>
        </div>
        <!--我的发票包-->
        <!--<div class="my-invoice card" @click="$router.push('/invoices')">-->
            <!--<div class="top line">-->
                <!--<img src="../img/invoice-small.png">-->
                <!--我的发票包-->
            <!--</div>-->
            <!--<div class="card-main">-->
                <!--<img src="../img/invoice-large.png">-->
            <!--</div>-->
        <!--</div>-->
    </div>
</template>

<script>
    import { getQueryString } from '../utils/common';
    import { mapState } from 'vuex';
    // import axios from 'axios';
    export default {
        data() {
            return {
                creditBg: require('../img/credit-bg.png'),
                starsmall: require('../img/star-small.png'),
                arrow: require('../img/arrow-small.png'),
                baoxiao: [
                    {
                        name: '未发k2',
                        img: require('../img/baoxiao-weifa.png'),
                        badge: this.num1
                    },
                    {
                        name: '审批中',
                        img: require('../img/baoxiao-shenhe.png'),
                        badge: this.num2
                    },
                    {
                        name: '待付款',
                        img: require('../img/baoxiao-daifukuan.png'),
                        badge: this.num3
                    },
                    {
                        name: '已付款',
                        img: require('../img/baoxiao-yifukuan.png')
                    },
                    {
                        name: '待评价',
                        img: require('../img/baoxiao-daipingjia.png'),
                        badge: this.num5
                    }
                ],
                common: [
                    {
                        name: '个人额度查询',
                        img: require('../img/gereneduchaxun.png'),
                        url: 'myquota'
                    },
                    {
                        name: '报销账户设置',
                        img: require('../img/baoxiaozhanghushezhi.png'),
                        url: 'bxaccount'
                    },
                    {
                        name: '代报销人设置',
                        img: require('../img/daibaoxiaorenshezhi.png'),
                        url: 'thirdbaoxiao'
                    },
                    {
                        name: '增值税开票信息',
                        img: require('../img/zengzhishui.png'),
                        url: 'vat'
                    },
                    {
                        name: '微账单',
                        img: require('../img/weizhangdan.png'),
                        url: 'mybill'
                    }
                ],
                chaxun: [
                    {
                        name: '通讯费报销单',
                        img: require('../img/tongxunfeibaoxiao.png')
                    },
                    {
                        name: '车辆费报销单',
                        img: require('../img/cheliangfeibaoxiao.png'),
                        type: 'car'
                    },
                    {
                        name: '交通费报销单',
                        img: require('../img/jiaotongfeibaoxiao.png')
                    },
                    {
                        name: '出差申请单',
                        img: require('../img/chuchaishenqing.png')
                    },
                    {
                        name: '差旅报销单',
                        img: require('../img/chailvbaoxiao.png'),
                        type: 'travel'
                    },
                    {
                        name: '事项申请单',
                        img: require('../img/shixiangshenqing.png')
                    },
                    {
                        name: '无合同付款单',
                        img: require('../img/wuhetongfukuan.png')
                    },
                    {
                        name: '合同',
                        img: require('../img/hetong.png'),
                        type: 'contract'
                    }
                ],
                nums: [],
                rank: -1,
                start: new Date().getTime(),
                // reloadUrl: 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx45362d8e0247a7c7&redirect_uri=http://t1.vanke.com:6888&response_type=code&scope=snsapi_userinfo&agentid=3&state=state#wechat_redirect'
                reloadUrl: 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx45362d8e0247a7c7&redirect_uri=http://t1.vanke.com:6888/grzxTest&response_type=code&scope=snsapi_userinfo&agentid=3&state=state#wechat_redirect'
            };
        },
        computed: {
            creditRank() {
                var rank = this.rank;
                if (rank <= 59) {
                    return 1;
                } else if (rank <= 75) {
                    return 2;
                } else if (rank <= 90) {
                    return 3;
                } else if (rank <= 100) {
                    return 4;
                } else {
                    return 0;
                }
            },
            ...mapState(['userNum', 'userInfo', 'avatar'])
        },
        mounted() {
            this.init();
            this.initLocData();
        },
        methods: {
            init () {
                let code = this.$route.query.code || getQueryString('code');
                if (code) {
                    console.log('链接后面有code');
                    if (!this.userNum) {
                        this.getUserNum(code);
                    } else {
                        this.getSessionid();
                    }
                } else {
                    console.log('链接后面没有code');
                    if (!this.userNum) {
                        window.location.href = this.reloadUrl;
                    } else {
                        this.getSessionid();
                    }
                }
            },
            initLocData () {
                console.log('初始化本地数据');
                let userInfo = localStorage.getItem('userInfo');
                let creditData = localStorage.getItem('creditData');
                var numsStored = localStorage.getItem('badges');
                if (userInfo) {
                    userInfo = JSON.parse(userInfo);
                    this.$store.commit('userInfo', userInfo);
                }
                if (creditData && creditData !== 'undefined') {
                    var data = JSON.parse(creditData);
                    this.rank = data.creditScore;
                }
                if (numsStored) {
                    this.nums = JSON.parse(numsStored);
                }
            },
            getUserNum (code) {
                console.log('获取用户信息');
                this.$http.get(`/vank/receipt/user_info1.do?code=${code}`).then(res => {
                    console.log('用户信息>>>', res.data);
                    let data = JSON.parse(res.data.data);
                    if (+data.errcode !== 0) {
                        if (+data.errcode === 40029) {
                            window.location.href = this.reloadUrl;
                        } else {
                            console.log(data.errmsg);
                        }
                    } else {
                        if (data.userid) {
                            const { userid, avatar } = data;
                            console.log(userid, avatar);
                            this.$store.commit('userNum', userid);
                            this.$store.commit('avatar', avatar);
                            this.avatar = avatar;
                            this.getSessionid();
                        } else {
                            console.log('没有关注');
                        }
                    }
                });
            },
            getSessionid() {
                let state = this.$route.query.state || getQueryString('state');
                if (state) this.$router.replace(state);
                // dcName Eastest（正式环境换成eas750）
                var url = this.HOST + '?method=loginEAS&userName=sysWS&password=sysWS&slnName=eas&dcName=eas750&language=L2&dbType=1';
                this.getBadges();
                if (this.userNum && sessionStorage.getItem('baoxiaoData')) {
                    return;
                }
                this.$http.get(url).then(res => {
                    var sessionId = res.data.msg;
                    this.$store.commit('sessionId', sessionId);
                    // setTimeout(() => this.saveAllBill(), 100);
                    this.getCredit(sessionId);
                    this.getUserInfo(sessionId);
                });
            },
            getCredit(sessionId) {
                var url = this.HOST + '?method=getCredits&userNum=' + this.userNum + '&sessionID=' + sessionId;
                this.$http.get(url).then(res => {
                    this.rank = res.data.creditScore;
                    localStorage.setItem('creditData', JSON.stringify(res.data));
                });
            },
            getUserInfo(sessionId) {
                console.log('获取费控用户信息');
                var url = this.HOST + '?method=getAccountBank&userNum=' + this.userNum + '&sessionID=' + sessionId;
                this.$http.get(url).then(res => {
                    if (res.data) {
                        let userInfo = res.data;
                        console.log('getAccountBank', userInfo);
                        this.$store.commit('userInfo', userInfo);
                        this.$store.commit('userNum', userInfo.userNum);
                    }
                });
            },
            goToDetail(name, src) {
                window.localStorage.setItem('billname', name);
                window.localStorage.setItem('billicon', src);
                this.$router.push('./singleList');
            },
            saveAllBill () {
                for (let key in this.LISTARR) {
                    let method = this.LISTARR[key];
                    let url = url = this.HOST + '?method=' + method + '&userNum=' + this.userNum;
                    if (method === 'listTravelBillWK') {
                        url = this.HOST + '?method=listTravelBillWK&unumber=' + this.userNum + '&sessionID=' + this.SESSIONID;
                    }
                    if (!localStorage.getItem(method)) {
                        this.$http.post(url).then(res => {
                            let data = res.data.t;
                            // sessionStorage.setItem(method, JSON.stringify(data));
                            localStorage.setItem(method, JSON.stringify(data));
                        });
                    }
                }
            },
            getBadges(sessionId) {
                console.log('请求Badges');
                /* eslint-disable no-unused-vars */
                let Arr = ['getBizAccountBills', 'getComputerAccounts', 'listTravelBillWK', 'getContractPayments', 'getNoContractPayments'];
                let data = [];
                let loadLen = 0;
                let allLen = Arr.length;
                let self = this;
                Arr.forEach(method => {
                    let url = this.HOST + '?method=' + method + '&userNum=' + this.userNum + '&sessionID=' + sessionId;
                    (method => {
                        this.$http.get(url).then(res => {
                            loadLen++;
                            let list = res.data.t || [];
                            console.log(loadLen, method, list);
                            data = data.concat(list);
                            localStorage.setItem(method, JSON.stringify(list));
                            // self.initBaoXiaoData(data);
                            if (loadLen === allLen) {
                                console.log('已经加载完所有报销单');
                                self.initBaoXiaoData(data);
                            }
                        });
                    })(method);
                });
            },
            initBaoXiaoData (arr) {
                let num1 = 0;
                let num2 = 0;
                let num3 = 0;
                let num4 = 0;
                let num5 = 0;
                localStorage.setItem('baoxiaoData', JSON.stringify(arr));
                for (var i = 0; i < arr.length; i++) {
                    var state1 = ['20', '25'];// 未发
                    var state2 = ['30', '145', '305']; // 审批中
                    var state3 = ['60', '65', '300', '210', '205']; // 待付款
                    var state4 = ['70', '45', '80']; // 已付款
                    var state5 = ['45', '60', '65', '70', '80']; // 待评价
                    let state = (arr[i].state + '') || (arr[i].FSTATE + '');
                    if (state1.indexOf(state) !== -1) {
                        num1++;
                    }
                    if (state2.indexOf(state) !== -1) {
                        num2++;
                    }
                    if (state3.indexOf(state) !== -1) {
                        num3++;
                    }
                    // if (state4.indexOf(state) !== -1) {
                    //     num4++;
                    // }
                    if ((state5.indexOf(state) !== -1) &&
                        (arr[i].isEvaluat === '0' || arr[i].ISEVALUAT === '0')) {
                        var date = arr[i].FBILLDATE || arr[i].billDate;
                        if (date > '2017-08-30') {
                            num5++;
                        }
                    }
                }
                let nums = [];
                nums.push(num1, num2, num3, num4, num5);
                this.nums = nums;
                localStorage.setItem('badges', JSON.stringify(self.nums));
            },
            emptyStorage() {
                window.sessionStorage.removeItem('bankName');
                // window.sessionStorage.removeItem('badges');
            }
        }
    };
</script>

<style lang="less" scoped>
    @import "../css/var.less";

    .home {
        padding-bottom: .2rem;
        .userinfo {
            overflow-x: hidden;
            position: relative;
            width: 100%;
            height: 2.1rem;
            padding: .4rem .28rem;
            background-color: @theme-color;
            color: #fff;
            margin-bottom: .2rem;
            .text {
                margin-left: .3rem;
                margin-top: .25rem;
                div {
                    line-height: 1;
                }
                .username {
                    font-size: @card-title-fsize;
                    margin-bottom: .2rem;
                }
                .account {
                    font-size: @sub-title-fsize;
                }
            }
            .credit {
                position: absolute;
                top: .75rem;
                right: -.26rem;
                padding-left: .24rem;
                padding-right: .1rem;
                height: .6rem;
                line-height: .62rem;

                font-size: .22rem;
                color: #fff;
                background-image: linear-gradient(90deg, rgba(29, 148, 197, 0.6), rgba(56, 92, 173, 0.6));
                border-radius: .3rem;

                .rank {
                    display: inline-block;
                    width: .2rem;
                    height: .2rem;
                    background-size: cover;
                }
                img {
                    height: .2rem;
                    margin-top: -0.04rem;
                    margin-right: .28rem;
                }
            }
        }
        .card {
            /*border-bottom: 1px solid #e0e0e0;*/
            margin-bottom: .2rem;
            .top {
                font-size: .3rem;
                color: @text-color1;
                border-bottom: 1px solid #e0e0e0;
            }

            &.baoxiao {
                .card-main {
                    .item {
                        width: 20%;
                        .img {
                            height: .62rem;
                        }
                        .icon {
                            width: .4rem;
                        }
                        border-bottom: none;
                    }
                }
            }
            &.my-invoice {
                text-align: center;
                .top {
                    img {
                        width: .36rem;
                        height: .36rem;
                        margin-top: -.06rem;
                        margin-right: .06rem;
                    }
                }
                .card-main {
                    height: 1.96rem;
                    line-height: 1.96rem;
                    img {
                        width: 1.34rem;
                    }
                }
            }
        }
    }
</style>
